package com.imooc.segmentTree;

/**
 * 求数组某个区间上的和
 */
public class NumArray {

    // sum[i]存储前i个元素和, sum[0] = 0
    // 即sum[i]存储nums[0...i-1]的和
    // sum(i, j) = sum[j + 1] - sum[i]
    private int[] sum;

    private int[] data;

    public NumArray(int[] arr) {
        data = new int[arr.length];
        for(int i = 0; i < arr.length; i++) {
            data[i] = arr[i];
        }
        sum = new int[arr.length + 1];
        sum[0] = 0;
        for(int i = 1; i < sum.length; i++) {
            sum[i] = sum[i - 1] + arr[i - 1];
        }
    }

    public void update(int index, int val) {
        data[index] = val;
        for(int i = index + 1; i < sum.length; i++)
            sum[i] = sum[i - 1] + data[i - 1];
    }

    public int sumRange(int i, int j) {
        return sum[j + 1] - sum[i];
    }
}
